package com.jwaoo.real2dui;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.content.Context;
import android.text.Html;
import android.text.Spanned;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationSet;
import android.view.animation.RotateAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.vr.cardboard.*;
import com.jwaoo.common.Constant;
import com.jwaoo.common.DensityUtil;
import com.jwaoo.common.MySharedPreferences;
import com.jwaoo.real2dui.R;

public class Real2DUiLayer implements OnClickListener {

	public static final String TAG = Real2DUiLayer.class.getSimpleName();

	public enum RealTipState {

		RealTipState_Video, RealTipState_Control
	}

	// 事件
	public static final int Real2DUiEvent_Back = 0;

	public static final int Real2DUiEvent_Add = 1;

	public static final int Real2DUiEvent_Sub = 2;

	public static final int Real2DUiEvent_Reset = 3;

	public static final int Real2DUiEvent_Switch = 4;

	public static final int Real2DUiEvent_Max = 5;

	public static final int Real2DUiEvent_Tip = 6;

	public static final int Real2DUiEvent_All = 7;

	public static final int Real2DUiAction_MoveStart = 10;

	public static final int Real2DUiAction_MoveEnd = 11;

	// context
	private Context context;
	// UI 根目录
	private RelativeLayout rootLayout;

	// 左边UI界面
	private LinearLayout leftUiLayout;

	// 切换视频和游戏
	private ImageView videoButton;

	// 切换视频和游戏外部ImageView
	private ImageView videoBaseButton;

	// 左侧需要隐藏区域布局
	private RelativeLayout leftInvisibleRelative;

	// 增加按键
	private ImageView addButton;

	// 减少按键
	private ImageView subButton;

	// 重置按键
	private ImageView resetButton;

	// 切换按键
	private ImageView switchButton;

	// 最大按键
	private ImageView maxButton;

	// 选择切换为Next图标
	private ImageView realNext;

	// 返回按键
	private ImageView backButton;

	// 右边UI界面
	private LinearLayout rightUiLayout;

	// 进度条
	// private ProgressBar progressBar;

	private Real2DUiEvent real2DUiEvent;

	private int lastX, lastY;
	private int firstX, firstY;
	private int screenWidth;
	private int screenHeight;
	private int leftUIPaddingAdd;

	private static final long DELAY_DOWNTIME = 500;
	private static final long DELAY_VIBRATOR = 100;
	private static final long ANIMATION_TIME = 500;

	private boolean isLongClick = false;
	private boolean LeftUiLeft = true;
	private boolean RightUiLeft = false;

	private View curTouchView;

	private boolean retuens = false;

	private boolean isVideo = true;

	private boolean uiMove = false;

	private TimerTask task;
	private Timer timer;

	private static final int TIMER_DELAY = 0;
	private static final int TIMER_PERIOD = 10;

	private static final int MOVE_UNIT = 1;
	private int count = 0;

	private static final int ANIMATION_INVISIBLE_DELAY = 500;
	private static final int ANIMATION_VISIBLE_DELAY = 1000;
	
	private static final int ANIMATION_VIDEO_ROTATE = 1000;
	
	private boolean isTouchMaxButton = false;//是否给Max添加选中状态
	
	private Rotate3dAnimation rotation;

	//Guide 相关View
	private ViewGroup view_guide;
	private RelativeLayout guide_real_root_relative;
	private RelativeLayout guide_real_video_root_Relative;
	private RelativeLayout guide_real_reset_root_relative;
	private RelativeLayout guide_real_switch_root_relative;
	private RelativeLayout guide_real_max_root_relative;


	private FrameLayout guide_real_video_frame;

	private ImageView guide_real_video;
	private ImageView guide_real_video_base;
	private ImageView guide_real_reset;
	private ImageView guide_real_switch;
	private ImageView guide_real_max;

	private TextView guide_real_video_tip;
	private TextView guide_real_reset_tip;
	private TextView guide_real_switch_tip;
	private TextView guide_real_max_tip;

	private int guideId = 0;

	public Real2DUiLayer(Context context) {

		this.context = context;

		initializeViewsWithLayoutId(R.layout.reallayer);

	}
	public Real2DUiLayer(Context context, boolean lands) {

		this.context = context;

		if (lands)
			initializeViewsWithLayoutIdLand(R.layout.reallayer_landscape);
		else
			initializeViewsWithLayoutId(R.layout.reallayer);
	}

	private void initializeViewsWithLayoutIdLand(int i){
		screenWidth = DensityUtil.getScreenRealWidth(context);
		screenHeight = DensityUtil.getScreenRealHeight(context);
		int videoGapPX = screenWidth - (screenHeight/9*16);
		videoGapPX =videoGapPX < 0?0:videoGapPX;
		leftUIPaddingAdd = videoGapPX/2;
		Log.d(TAG,"screenWidth : " + screenWidth + " screenHeight : " + screenHeight + " leftUIPaddingAdd : " + leftUIPaddingAdd);

		timer = new Timer();

		rootLayout = (RelativeLayout) LayoutInflater.from(context).inflate(i,
				null, false);

		leftUiLayout = (LinearLayout) rootLayout.findViewById(R.id.leftLinear);

		videoButton = (ImageView) rootLayout.findViewById(R.id.real_video);

		videoBaseButton = (ImageView) rootLayout.findViewById(R.id.real_video_base);

		leftInvisibleRelative = (RelativeLayout) rootLayout
				.findViewById(R.id.leftInvisibleRelative);

		resetButton = (ImageView) rootLayout.findViewById(R.id.real_reset);

		switchButton = (ImageView) rootLayout.findViewById(R.id.real_switch);

		maxButton = (ImageView) rootLayout.findViewById(R.id.real_max);

		realNext = (ImageView) rootLayout.findViewById(R.id.real_next);

		rightUiLayout = (LinearLayout) rootLayout
				.findViewById(R.id.rightLinear);

		backButton = (ImageView) rootLayout.findViewById(R.id.real_close);

		leftUiLayout.setOnTouchListener(new MyOnTouchListener());

		rootLayout.setOnClickListener(this);

		resetButton.setOnClickListener(this);

		switchButton.setOnClickListener(this);

		videoButton.setOnClickListener(this);

		backButton.setOnClickListener(this);

		int leftPaddingCurrent = leftUiLayout.getPaddingLeft();
		leftUiLayout.setPadding(leftPaddingCurrent + leftUIPaddingAdd,0,0,0);

		checkGuide();

	}

	private void initializeViewsWithLayoutId(int i) {

		screenWidth = DensityUtil.getScreenRealWidth(context);
		screenHeight = DensityUtil.getScreenRealWidth(context);

		timer = new Timer();

		rootLayout = (RelativeLayout) LayoutInflater.from(context).inflate(i,
				null, false);

		leftUiLayout = (LinearLayout) rootLayout.findViewById(R.id.leftLinear);

		videoButton = (ImageView) rootLayout.findViewById(R.id.real_video);
		
		videoBaseButton = (ImageView) rootLayout.findViewById(R.id.real_video_base);

		leftInvisibleRelative = (RelativeLayout) rootLayout
				.findViewById(R.id.leftInvisibleRelative);

		addButton = (ImageView) rootLayout.findViewById(R.id.real_add);

		subButton = (ImageView) rootLayout.findViewById(R.id.real_sub);

		resetButton = (ImageView) rootLayout.findViewById(R.id.real_reset);

		switchButton = (ImageView) rootLayout.findViewById(R.id.real_switch);

		maxButton = (ImageView) rootLayout.findViewById(R.id.real_max);

		realNext = (ImageView) rootLayout.findViewById(R.id.real_next);

		rightUiLayout = (LinearLayout) rootLayout
				.findViewById(R.id.rightLinear);

		backButton = (ImageView) rootLayout.findViewById(R.id.real_close);

		leftUiLayout.setOnTouchListener(new MyOnTouchListener());
		
		rootLayout.setOnClickListener(this);

		addButton.setOnClickListener(this);

		subButton.setOnClickListener(this);

		resetButton.setOnClickListener(this);

		switchButton.setOnClickListener(this);

		videoButton.setOnClickListener(this);

		backButton.setOnClickListener(this);


	}


	private void checkGuide(){
		boolean isShowGuide = MySharedPreferences.getBoolean2(context, MySharedPreferences.NAME_NOT_CLEAR, Constant.SP_GUIDE_REAL_2D_LANDS);
		if(!isShowGuide){
			initGuideView();
			MySharedPreferences.save2(context,MySharedPreferences.NAME_NOT_CLEAR, Constant.SP_GUIDE_REAL_2D_LANDS,true);
		}

    }

	private void initGuideView() {
		view_guide = (ViewGroup) LayoutInflater.from(context).inflate(R.layout.guide_view_video, null);
		rootLayout.addView(view_guide);
		guide_real_root_relative = (RelativeLayout) view_guide.findViewById(R.id.guide_real_root_relative);
		guide_real_video_root_Relative = (RelativeLayout) view_guide.findViewById(R.id.guide_real_video_root_Relative);
		guide_real_reset_root_relative = (RelativeLayout) view_guide.findViewById(R.id.guide_real_reset_root_relative);
		guide_real_switch_root_relative = (RelativeLayout) view_guide.findViewById(R.id.guide_real_switch_root_relative);
		guide_real_max_root_relative = (RelativeLayout) view_guide.findViewById(R.id.guide_real_max_root_relative);

		guide_real_video_frame = (FrameLayout) view_guide.findViewById(R.id.guide_real_video_frame);

		guide_real_video = (ImageView) view_guide.findViewById(R.id.guide_real_video);
		guide_real_video_base = (ImageView) view_guide.findViewById(R.id.guide_real_video_base);
		guide_real_reset = (ImageView) view_guide.findViewById(R.id.guide_real_reset);
		guide_real_switch = (ImageView) view_guide.findViewById(R.id.guide_real_switch);
		guide_real_max = (ImageView) view_guide.findViewById(R.id.guide_real_max) ;


		guide_real_video_tip = (TextView) view_guide.findViewById(R.id.guide_real_video_tip);
		guide_real_reset_tip = (TextView) view_guide.findViewById(R.id.guide_real_reset_tip);
		guide_real_switch_tip = (TextView) view_guide.findViewById(R.id.guide_real_switch_tip);
		guide_real_max_tip = (TextView) view_guide.findViewById(R.id.guide_real_max_tip);

		int leftPaddingCurrent = guide_real_root_relative.getPaddingLeft();
		guide_real_root_relative.setPadding(leftPaddingCurrent + leftUIPaddingAdd,0,0,0);

		guide_real_video_frame.setVisibility(View.INVISIBLE);

		guideId = 1;
		showGuide(guideId);

		view_guide.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                showGuide(++guideId);
            }
        });
	}

	private void showGuide(int guideId){
	    Log.d(TAG,"guideId : " + guideId);
        guide_real_video_root_Relative.setVisibility(View.INVISIBLE);
        guide_real_reset_root_relative.setVisibility(View.INVISIBLE);
        guide_real_switch_root_relative.setVisibility(View.INVISIBLE);
        guide_real_max_root_relative.setVisibility(View.INVISIBLE);
		guide_real_video.setVisibility(View.INVISIBLE);
		guide_real_video_base.setVisibility(View.INVISIBLE);
		guide_real_reset.setVisibility(View.INVISIBLE);
		guide_real_switch.setVisibility(View.INVISIBLE);
		guide_real_max.setVisibility(View.INVISIBLE);

		if(guideId != 1 || guideId != 2){
//			videoButton.setVisibility(View.VISIBLE);
//			videoBaseButton.setVisibility(View.VISIBLE);
			guide_real_video_frame.setVisibility(View.INVISIBLE);
		}
		resetButton.setVisibility(View.VISIBLE);
		switchButton.setVisibility(View.VISIBLE);
		maxButton.setVisibility(View.VISIBLE);

		int event = -1;

        if(guideId == 1){
			guide_real_video_frame.setVisibility(View.INVISIBLE);
//			videoButton.setImageResource(R.drawable.device_video);
            guide_real_video_root_Relative.setVisibility(View.VISIBLE);
			guide_real_video.setVisibility(View.VISIBLE);
			guide_real_video_base.setVisibility(View.VISIBLE);
			//guide_real_video.setImageResource(R.drawable.device_video);
			Spanned videoTip = Html.fromHtml(context.getResources().getString(R.string.guide_2d_video));
            guide_real_video_tip.setText(videoTip);
			event = Real2DUiEvent_Tip;
        }else if(guideId == 2){
			guide_real_video_frame.setVisibility(View.INVISIBLE);
//			videoButton.setImageResource(R.drawable.device_control);
            guide_real_video_root_Relative.setVisibility(View.VISIBLE);
			guide_real_video.setVisibility(View.VISIBLE);
			guide_real_video_base.setVisibility(View.VISIBLE);
			//guide_real_video.setImageResource(R.drawable.device_control);
			Spanned interactiveTip = Html.fromHtml(context.getResources().getString(R.string.guide_2d_interactive));
            guide_real_video_tip.setText(interactiveTip);
			event = Real2DUiEvent_Tip;
        }else if(guideId == 3){
			resetButton.setVisibility(View.INVISIBLE);
            guide_real_reset_root_relative.setVisibility(View.VISIBLE);
			guide_real_reset.setVisibility(View.VISIBLE);
			//guide_real_reset.setImageResource(R.drawable.functionbar_fullshot_n);
			Spanned fullShotTip = Html.fromHtml(context.getResources().getString(R.string.guide_2d_full_shot));
            guide_real_reset_tip.setText(fullShotTip);
			//event = Real2DUiEvent_Reset;
        }else if(guideId == 4){
			resetButton.setVisibility(View.INVISIBLE);
            guide_real_reset_root_relative.setVisibility(View.VISIBLE);
			guide_real_reset.setVisibility(View.VISIBLE);
			//guide_real_reset.setImageResource(R.drawable.functionbar_closeup_n);
			Spanned closeUpTip = Html.fromHtml(context.getResources().getString(R.string.guide_2d_close_up));
            guide_real_reset_tip.setText(closeUpTip);
			event = Real2DUiEvent_Reset;
        }else if(guideId == 5){
			switchButton.setVisibility(View.INVISIBLE);
            guide_real_switch_root_relative.setVisibility(View.VISIBLE);
			guide_real_switch.setVisibility(View.VISIBLE);
            guide_real_reset.setImageResource(R.drawable.switch_n);
			Spanned changePositionTip = Html.fromHtml(context.getResources().getString(R.string.guide_2d_change_position));
			guide_real_switch_tip.setText(changePositionTip);
			event = Real2DUiEvent_Switch;
        }else if(guideId == 6){
			maxButton.setVisibility(View.INVISIBLE);
            guide_real_max_root_relative.setVisibility(View.VISIBLE);
			guide_real_max.setVisibility(View.VISIBLE);
			guide_real_max.setImageResource(R.drawable.g_n);
			Spanned maxTip = Html.fromHtml(context.getResources().getString(R.string.guide_2d_max));
			guide_real_max_tip.setText(maxTip);
			event = Real2DUiEvent_Max;
        }else if(guideId == 7){
            rootLayout.removeView(view_guide);
			resetButton.setVisibility(isVideo == true?View.INVISIBLE:View.VISIBLE);
        }
		Log.d(TAG, "showGuide event=" + event);
		if (event != -1 && real2DUiEvent != null) {
			real2DUiEvent.onEvent(event);
		}

    }

	// leftUI是否在移动
	public boolean can2DUIMove() {
		return uiMove;
	}

	private class MyOnTouchListener implements OnTouchListener {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			Log.d(TAG, "onTouch event action : " + event.getAction());
			switch (event.getAction()) {
			case MotionEvent.ACTION_DOWN:
				isLongClick = false;
				startLongClick();
				firstX = (int) event.getRawX();
				firstY = (int) event.getRawY();
				lastX = (int) event.getRawX();
				lastY = (int) event.getRawY();
				isTouchMaxButton = isTouchPointInView(maxButton, lastX, lastY);
				Log.d(TAG, "isTouchMaxButton down : " + isTouchMaxButton);
				if (isTouchMaxButton) {
					setMaxSelector(true);
				}
				break;
			case MotionEvent.ACTION_MOVE:
				int nowX = (int) event.getRawX();
				int nowY = (int) event.getRawY();
				int moveX = nowX - lastX;
				int moveY = nowY - lastY;
				int top = v.getTop() + moveY;
				int bottom = v.getBottom() + moveY;
				int left = v.getLeft() + moveX;
				int right = v.getRight() + moveX;

				lastX = (int) event.getRawX();
				lastY = (int) event.getRawY();

				if (isLongClick) {
					// 长按时Move
					v.layout(left, v.getTop(), right,
							v.getHeight() + v.getTop());
					// 通知界面
					uiMove = true;
					onMyMove(Real2DUiAction_MoveStart);

				}
				break;
			case MotionEvent.ACTION_UP:
				Log.d(TAG, "isTouchMaxButton up : " + isTouchMaxButton);
				if (isTouchMaxButton) {
					setMaxSelector(false);
				}
				cancelLongClick();
				uiMove = false;
				onMyMove(Real2DUiAction_MoveEnd);

				lastX = (int) event.getRawX();
				lastY = (int) event.getRawY();

				// 视为单机事件(else视为Move事件)
				if (Math.abs(firstX - lastX) < 20) {
					if(isTouchMaxButton){
						onMyClick(v, lastX, lastY);
						return false;
					}
				}

				// Move时动画移动
				if (Math.abs(firstX - lastX) >= 6 && isLongClick) {
					if (lastX < screenWidth / 2) {
						startLeftAnimation(v, true);
						startRightAnimation(rightUiLayout, false);
					} else {
						startLeftAnimation(v, false);
						startRightAnimation(rightUiLayout, true);
					}
				}
				isLongClick = false;
			}
			return true;
		}
	}
	
	/**
	 * Max按钮设置selector背景
	 * 
	 * @param isPressed
	 */
	private void setMaxSelector(boolean isPressed){
		
		if(isPressed){
			
			maxButton.setImageResource(R.drawable.g_s);
			
		}else{
			
			maxButton.setImageResource(R.drawable.g_n);
			
		}
		
		
	}

	/**
	 * 长按震动
	 */
	private void startLongClick() {

		cancelLongClick();

		task = new TimerTask() {
			public void run() {

				((Activity) context).runOnUiThread(new Runnable() {

					@Override
					public void run() {
						// 设置震动
						VibratorUtil.vibrate(context, DELAY_VIBRATOR);
						isLongClick = true;

					}
				});

			}
		};

		timer.schedule(task, DELAY_DOWNTIME);
	}

	/**
	 * 取消震动task
	 */
	private void cancelLongClick() {
		if (task != null) {

			task.cancel();

			task = null;

		}
	}

	private class MyAnimationListener implements AnimationListener{
		private boolean near;
		private boolean first;
		private ImageView currentResetBtn;
		public MyAnimationListener(boolean near, boolean first,ImageView currentResetBtn){
			this.near = near;
			this.first = first;
			this.currentResetBtn = currentResetBtn;
		}
		@Override
		public void onAnimationStart(Animation animation) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onAnimationEnd(Animation animation) {
			// TODO Auto-generated method stub
			Log.d(TAG, "near="+near + " first="+first);
			if (!near){
				if(currentResetBtn.getId() == R.id.real_reset){
					currentResetBtn.setImageResource(R.drawable.functionbar_fullshot_selector);
				}else if(currentResetBtn.getId() == R.id.guide_real_reset){
					currentResetBtn.setImageResource(R.drawable.functionbar_fullshot_n);
				}

			}else{
				if(currentResetBtn.getId() == R.id.real_reset){
					currentResetBtn.setImageResource(R.drawable.functionbar_closeup_selector);
				}else if(currentResetBtn.getId() == R.id.guide_real_reset){
					currentResetBtn.setImageResource(R.drawable.functionbar_closeup_n);
				}
			}
			if (first){
				AnimationSet set = getAnimationSet(near, false,currentResetBtn);

				//resetButton.setAnimation(set);
				//set.startNow();
				currentResetBtn.startAnimation(set);
			}
		}

		@Override
		public void onAnimationRepeat(Animation animation) {
			// TODO Auto-generated method stub

		}

	}

	private AnimationSet getAnimationSet(boolean near, boolean first,ImageView currentResetBtn){
		float start, end;
		if (first){
			start = 0f;
			end = 180f;
		}else{
			start = 180f;
			end = 360f;
		}
		RotateAnimation rotateAnimation = new RotateAnimation(start, end,
				Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
				0.5f);
		rotateAnimation.setDuration(ANIMATION_VIDEO_ROTATE/2);// 设置动画持续时间
		rotateAnimation.setFillAfter(true);

		if (first){
			start = 1.0f;
			end = 0.1f;
		}else{
			start = 0.1f;
			end = 1.0f;
		}
		AlphaAnimation alphaAnimation = new AlphaAnimation(start, end);
		alphaAnimation.setDuration(ANIMATION_VIDEO_ROTATE/2);// 设置动画持续时间
		alphaAnimation.setFillAfter(true);
		AnimationSet set = new AnimationSet(true);

		set.addAnimation(rotateAnimation);
		set.addAnimation(alphaAnimation);
		set.setAnimationListener(new MyAnimationListener(near, first,currentResetBtn));
		return set;
	}

	public void set2DNear(boolean near){

		Log.e(TAG, "set2DNear="+near);

		AnimationSet set = null;

		if(resetButton.getVisibility() == View.VISIBLE){
			//resetButton.setAnimation(set);
			//set.startNow();
			set = getAnimationSet(near, true,resetButton);
			resetButton.startAnimation(set);
		}else if(guide_real_reset != null && guide_real_reset.getVisibility() == View.VISIBLE){
			set = getAnimationSet(near, true,guide_real_reset);
			guide_real_reset.startAnimation(set);
		}
	}


	/**
	 * 游戏视频切换外部旋转动画
	 */
	private void rotateAnimation(ImageView currentBaseBtn) {
		RotateAnimation rotateAnimation = new RotateAnimation(180f, 0f,
				Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
				0.5f);
		
		rotateAnimation.setDuration(ANIMATION_VIDEO_ROTATE);// 设置动画持续时间
		rotateAnimation.setFillAfter(true);
		currentBaseBtn.setAnimation(rotateAnimation);
		rotateAnimation.startNow();
	}

	/**
	 * 视频切换3D翻转动画
	 * 
	 * @param start
	 * @param end
	 */
	private void flip3DAnimation(float start, float end,final ImageView currentVideoBtn) {
		// 计算中心点
		final float centerX = currentVideoBtn.getWidth() / 2.0f;
		final float centerY = currentVideoBtn.getHeight() / 2.0f;

		rotation = new Rotate3dAnimation(
				(ContextThemeWrapper) context, start, end, centerX, centerY,
				1.0f, true);
		rotation.setDuration(ANIMATION_VIDEO_ROTATE/2);
		rotation.setFillAfter(true);
		rotation.setInterpolator(new AccelerateInterpolator());

		rotation.setAnimationListener(new AnimationListener() {

			@Override
			public void onAnimationStart(Animation animation) {
			}

			@Override
			public void onAnimationRepeat(Animation animation) {
			}

			@Override
			public void onAnimationEnd(Animation animation) {
				if (retuens) {
					retuens = false;

					if (isVideo) {
						currentVideoBtn.setImageResource(R.drawable.device_video);
					} else {
						currentVideoBtn.setImageResource(R.drawable.device_control);
					}

					currentVideoBtn.clearAnimation();

					flip3DAnimation(90, 0,currentVideoBtn);
				}
			}
		});
		currentVideoBtn.startAnimation(rotation);
	}

	private void startRightAnimation(final View view, boolean isLeft) {
		Log.d(TAG, "startRightAnimation");
		if (isLeft) {
			if (!LeftUiLeft && !RightUiLeft) {
				TranslateAnimation tAnimL = new TranslateAnimation(0,
						-(screenWidth - view.getWidth()), 0, 0);
				tAnimL.setDuration(ANIMATION_TIME);
				tAnimL.setFillAfter(true);
				tAnimL.setInterpolator(new AccelerateDecelerateInterpolator());
				view.startAnimation(tAnimL);
				RightUiLeft = true;

				tAnimL.setAnimationListener(new AnimationListener() {

					@Override
					public void onAnimationStart(Animation animation) {
					}

					@Override
					public void onAnimationRepeat(Animation animation) {
					}

					@Override
					public void onAnimationEnd(Animation animation) {
						int left = view.getLeft()
								- (screenWidth - view.getWidth());
						int top = view.getTop();
						int width = view.getWidth();
						int height = view.getHeight();
						view.clearAnimation();
						view.layout(left, top, left + width, top + height);

					}
				});
			}
		} else {
			if (LeftUiLeft && RightUiLeft) {
				TranslateAnimation tAnimR = new TranslateAnimation(0,
						(screenWidth - view.getWidth()), 0, 0);
				tAnimR.setDuration(ANIMATION_TIME);
				tAnimR.setFillAfter(true);
				tAnimR.setInterpolator(new AccelerateDecelerateInterpolator());
				view.startAnimation(tAnimR);
				RightUiLeft = false;

				tAnimR.setAnimationListener(new AnimationListener() {

					@Override
					public void onAnimationStart(Animation animation) {
					}

					@Override
					public void onAnimationRepeat(Animation animation) {
					}

					@Override
					public void onAnimationEnd(Animation animation) {
						int left = view.getLeft()
								+ (screenWidth - view.getWidth());
						int top = view.getTop();
						int width = view.getWidth();
						int height = view.getHeight();
						view.clearAnimation();
						view.layout(left, top, left + width, top + height);
					}
				});
			}
		}
	}

	private void startLeftAnimation(final View view, final boolean isLeft) {

		LeftUiLeft = isLeft;

		if (task != null) {
			count = 0;
			task.cancel();
			task = null;
		}

		task = new TimerTask() {
			public void run() {
				((Activity) context).runOnUiThread(new Runnable() {
					@Override
					public void run() {
						count++;
						int left = 0;
						int right = 0;
						if (isLeft) {
							left = view.getLeft() - MOVE_UNIT * count;
							right = view.getRight() - MOVE_UNIT * count;
						} else {
							left = view.getLeft() + MOVE_UNIT * count;
							right = view.getRight() + MOVE_UNIT * count;
						}
						if (left < 0 || right > screenWidth) {
							if (left < 0) {
								left = 0;
								right = left + view.getWidth();
							}
							if (right > screenWidth) {

								right = screenWidth;

								left = right - view.getWidth();
							}
							if (task != null) {
								count = 0;
								task.cancel();
								task = null;
							}
						}
						Log.d(TAG, "left : " + left + " right : " + right);
						view.layout(left, view.getTop(), right,
								view.getHeight() + view.getTop());
					}
				});
			}
		};
		timer.schedule(task, TIMER_DELAY, TIMER_PERIOD);
	}

	// 绑定到activity上
	public void attachUiLayerToActivity(final Context activityContext) {

		if (activityContext == null || !(activityContext instanceof Activity)) {

			throw new RuntimeException(
					"A valid activityContext must be provided.");
		} else {

			ThreadUtils.runOnUiThread(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub

					((Activity) activityContext).addContentView(rootLayout,
							new android.widget.RelativeLayout.LayoutParams(-1,
									-1));

				}
			});

		}
	}

	/**
	 * 显示进度
	 * 
	 * @param progress
	 */
	public void showProgress(final int progress) {

		ThreadUtils.runOnUiThread(new Runnable() {

			@Override
			public void run() {

				// progressBar.setProgress(progress);
			}
		});

	}

	/**
	 * 设置左边ui的可见性
	 * 
	 * @param isVisible
	 */
	public void setLeftUiVisible(final boolean isVisible) {

		ThreadUtils.runOnUiThread(new Runnable() {

			@Override
			public void run() {

				leftInvisibleRelative.setVisibility(isVisible ? View.VISIBLE
						: View.INVISIBLE);

				maxButton.setVisibility(isVisible ? View.VISIBLE
						: View.INVISIBLE);

				rightUiLayout.setVisibility(isVisible ? View.VISIBLE
						: View.INVISIBLE);

			}
		});

	}

	/**
	 * 设置提示状态
	 * 
	 * @param state
	 */
	public void setRealTipState(RealTipState state) {

		setRealTipState(state, true);

	}

	/**
	 * 
	 * @param state
	 * @param isAnimation
	 */
	public void setRealTipState(final RealTipState state,
			final boolean isAnimation) {
		// TODO isAnimation = false第一次不显示动画效果

		((Activity) context).runOnUiThread(new Runnable() {

			@Override
			public void run() {
				if (videoButton.getVisibility() == View.VISIBLE){
					realTipAnimation(state, isAnimation, videoButton, videoBaseButton);
				}else if(guide_real_video != null && guide_real_video.getVisibility() == View.VISIBLE){
					realTipAnimation(state, isAnimation, guide_real_video, guide_real_video_base);
				}
			}
		});

	}

	/**
	 * 视频或者游戏按钮选择动画
	 * 
	 * @param state
	 * @param isAnimation
	 */
	private void realTipAnimation(RealTipState state, boolean isAnimation,ImageView currentVideoBtn,ImageView currentBaseBtn) {
		if (isAnimation) {
			
			rotateAnimation(currentBaseBtn);
			
			if (state == RealTipState.RealTipState_Video) {

				isVideo = true;

			} else if (state == RealTipState.RealTipState_Control) {

				isVideo = false;

			}
			
			//先取消上一次动画
			if(rotation!=null)
			rotation.cancel();
			
			flip3DAnimation(0, 90,currentVideoBtn);

			retuens = true;

		} else {

			if (state == RealTipState.RealTipState_Video) {

				currentVideoBtn.setImageResource(R.drawable.device_video);

			} else if (state == RealTipState.RealTipState_Control) {

				currentVideoBtn.setImageResource(R.drawable.device_control);

			}

		}
		resetButton.setVisibility(isVideo == true?View.INVISIBLE:View.VISIBLE);
	}

	/**
	 * 控制NextTip显示
	 * 
	 * @param visible
	 * @param alpha
	 */
	public void setNextTipVisible(boolean visible, float alpha) {
		// TODO 中间500ms显示出，然后1000ms消失
		if (visible) {

			((Activity) context).runOnUiThread(new Runnable() {

				@Override
				public void run() {

					nextImageVisible();

				}
			});

		}

	}

	/**
	 * Next选择图标动画
	 */
	private void nextImageVisible() {
		AlphaAnimation animVisible = new AlphaAnimation(0, 1);
		realNext.startAnimation(animVisible);
		animVisible.setFillAfter(true);
		animVisible.setDuration(ANIMATION_INVISIBLE_DELAY);
		realNext.startAnimation(animVisible);

		animVisible.setAnimationListener(new AnimationListener() {

			@Override
			public void onAnimationStart(Animation animation) {
			}

			@Override
			public void onAnimationRepeat(Animation animation) {
			}

			@Override
			public void onAnimationEnd(Animation animation) {
				AlphaAnimation animInVisible = new AlphaAnimation(1, 0);
				realNext.startAnimation(animInVisible);
				animInVisible.setFillAfter(true);
				animInVisible.setDuration(ANIMATION_VISIBLE_DELAY);
				realNext.startAnimation(animInVisible);

			}
		});
	}

	/**
	 * 获取根View
	 * 
	 * @return
	 */
	public View getRootView() {

		return rootLayout;
	}

	/**
	 * 设置回调
	 * 
	 * @param real2DUiEvent
	 */
	public void setReal2DUiEvent(Real2DUiEvent real2DUiEvent) {

		this.real2DUiEvent = real2DUiEvent;
	}

	private void onMyMove(int uiAction) {

		if (real2DUiEvent != null) {

			real2DUiEvent.onMove(uiAction);

		}

	}

	public void onMyClick(View v, int lastX, int lastY) {

		int event = -1;

		getCurTouchView(v, lastX, lastY);

		if (curTouchView == null)
			return;

		if (curTouchView.getId() == R.id.real_max) {

			event = Real2DUiEvent_Max;

		}

		Log.d(TAG, "event=" + event);
		if (event != -1 && real2DUiEvent != null) {

			real2DUiEvent.onEvent(event);
		}
	}

	@Override
	public void onClick(View v) {
       Log.d(TAG,"real_close time 111 : " + System.currentTimeMillis());
		int event = -1;

		if (v.getId() == R.id.real_close) {

			event = Real2DUiEvent_Back;

		} else if (v.getId() == R.id.real_add) {

			event = Real2DUiEvent_Add;

		} else if (v.getId() == R.id.real_sub) {

			event = Real2DUiEvent_Sub;

		} else if (v.getId() == R.id.real_reset) {

			event = Real2DUiEvent_Reset;

		} else if (v.getId() == R.id.real_switch) {

			event = Real2DUiEvent_Switch;

		} else if (v.getId() == R.id.real_video) {

			event = Real2DUiEvent_Tip;

		} else if (v.getId() == R.id.reallayer) {

			event = Real2DUiEvent_All;
		}

		Log.d(TAG, "event=" + event);
		if (event != -1 && real2DUiEvent != null) {
			Log.d(TAG,"real_close time 222 : " + System.currentTimeMillis());
			real2DUiEvent.onEvent(event);
			Log.d(TAG,"real_close time 333 : " + System.currentTimeMillis());
		}
	}

	private void getCurTouchView(View v, int lastX, int lastY) {

		if (v instanceof ViewGroup) {

			ViewGroup viewGroup = ((ViewGroup) v);

			int count = viewGroup.getChildCount();

			for (int i = 0; i < count; i++) {

				View curView = viewGroup.getChildAt(i);

				if (curView instanceof ViewGroup) {

					getCurTouchView(curView, lastX, lastY);

				} else {
					boolean isTouch = isTouchPointInView(curView, lastX, lastY);
					if (isTouch) {
						curTouchView = curView;
					}
				}
			}

		} else {

			curTouchView = v;

		}
	}

	// 触摸(x,y)是否在view的区域内
	private boolean isTouchPointInView(View view, int x, int y) {
		if (view == null) {
			return false;
		}
		int[] location = new int[2];
		view.getLocationOnScreen(location);
		int left = location[0];
		int top = location[1];
		int right = left + view.getMeasuredWidth();
		int bottom = top + view.getMeasuredHeight();
		// view.isClickable() &&
		if (y >= top && y <= bottom && x >= left && x <= right) {
			return true;
		}
		return false;
	}

	public interface Real2DUiEvent {

		public void onEvent(int uiEvent);

		public void onMove(int uiAction);

	}
}
